<template>
	<div>
		  <!-- <div>
    <div class="blank"></div>
    <div class="list">
			<div  v-for="(competition, index) in competitions"  :key="index" class="box1" >
				<competitionCard
        class="item"
        :competition="competition"
        />
				<div class="buttons">
			    <el-button
           type="primary"
           size="small"
           link
            @click="edit(competition)"
            >
            <i-ep-edit />
		      	编辑
            </el-button>
		      	<el-button
            type="primary"
            size="small"
            link
            @click="del(competition.id)"
           >
           <i-ep-delete />
		      	删除
          </el-button>
	    	</div>
			</div>    
    </div>	
  </div> -->

	<el-card>
      <div>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="deleteClick()"
          v-hasPerm="['resource:competition:del']"
          >
					<i-ep-delete />
					批量删除
					</el-button>

				<el-button
          type="primary"
          @click="add()"
		  v-hasPerm="['resource:competition:add']"
          > 
					<el-icon>
        		 <Plus/>
        </el-icon>
				新增竞赛
				</el-button
        >
      </div>
   </el-card>

	<el-card>
      <div>
        <el-form>
          <el-form-item>
            <el-table
					  	:data="competitions"
						  :header-cell-style="{'text-align':'center'}"
    			:cell-style="{'text-align':'center'}"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="50" align="center" />
              <!-- <el-table-column fixed prop="id" label="序号" width="100" /> -->
			  <!-- <el-table-column  label="序号" width="100">
    			<template #default="scope">
					<span>{{scope.$index+1}}</span>
     			 </template>
   			 </el-table-column> -->
				<el-table-column
                fixed
                type="index"
                :index="indexMethod"
                label="序号"
                width="80"
              />
              <el-table-column prop="title" label="标题" width="120" />
							<el-table-column prop="competitionTime" label="竞赛时间" width="300" />
              <el-table-column prop="registrationDeadline" label="报名截止时间" width="170" />
              <el-table-column label="封面" width="200px">
                <template #="{ row }">
                  <!-- <img :src="row.coverImage" alt="" style="width: 100px; height: 100px" /> -->
				  <el-image
      							style="width: 100px; height: 100px"
     							 :src="row.coverImage"
     							 :zoom-rate="1.2"
      							:max-scale="7"
     							 :min-scale="0.2"
     							 :preview-src-list="[row.coverImage]"
										:preview-teleported="true"
										hide-on-click-modal
   							 />
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="240">
                <template #default="scope">							
                  <!-- <el-button type="primary" @click="edit(scope.row)"
                    >详情</el-button
                  > -->
                  <el-button type="warning" @click="edit(scope.row)"   v-hasPerm="['resource:competition:update']"
                    >编辑</el-button
                  >
                  <el-button type="danger" @click="del(scope.row.id)"   v-hasPerm="['resource:competition:del']"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

			 <!-- 分页搜索 -->
			<div
              style="
                display: flex;
                justify-content: center;
                width: 100%;
                margin-top: 15px;
              "
            >
              <el-pagination
                background
                layout="sizes, prev,slot, next, jumper"
                :page-count="pageTotal"
                :page-sizes="[10, 20, 30, 50]"
                :current-page="activePager"
                @update:current-page="pageChange"
                @update:page-size="sizeChange"
                :default-current-page="1"
                :default-page-size="10"
              >
                <div class="pagination">
                  <span
                    class="pagination__item"
                    :class="{ active: activePager === pager }"
                    v-for="pager in pageArr"
                    :key="pager"
                    @click="pageChange(pager)"
                  >
                    {{ pager }}
                  </span>
                </div>
              </el-pagination>
            </div>
            <!-- 分页搜索 -->

			</el-form-item>
        </el-form>
      </div>
		</el-card>


	 <!-- 修改博客弹窗 -->
	 <el-dialog
      :title="editDialog.title"
      v-model="editDialog.visible"
      width="100%"
      @close="closeEditDialog"
    >
		<div class="box">
	  <el-form
		:model="ruleForm"
		:rules="rules"
		ref="ruleFormEditRef"
		label-width="110px"
		class="demo-ruleForm"
		size="large"
		label-position="left"
		validate-on-rule-change
		style="width: 85%"
	  >
		<el-form-item label="标题" prop="title" style="width: 100%">
		  <el-input
			style="width: 100%"
			type="text"
			v-model="ruleForm.title"
			placeholder="输入标题..."
		  ></el-input>
		</el-form-item>
  
		<el-form-item label="内容" prop="content" style="width: 100%">
		  <mavon-editor
			v-model="ruleForm.content"
			ref="md"
			@imgAdd="imgAdd"
			style="width: 100%; height: 430px"
		  />
		</el-form-item>
  
		<el-form-item label="封面" prop="coverImage">
		  <el-upload
		    :action="File_API.OTHER_URL"
			:show-file-list="false"
			:on-success="handleAvatarSuccess"
			:before-upload="beforeAvatarUpload"
			class="avatar-uploader"
		  >
			<img v-if="imageUrl" :src="imageUrl" class="avatar" />
			<!-- <el-icon v-else name="UploadFilled" class="avatar-uploader-icon"></el-icon> -->
			<el-icon v-else class="avatar-uploader-icon">
				 <UploadFilled/>
			</el-icon>
		  </el-upload>
		</el-form-item>
  
		<el-form-item label="竞赛时间" prop="competitionTime" style="width: 50%">
			<el-date-picker
     		 v-model="dateArr"
			 @change="dateChange"
			 value-format="YYYY-MM-DD HH:mm:ss"
    		 type="datetimerange"		
			 range-separator="-"
     		 start-placeholder="开始时间"
     		 end-placeholder="结束时间"
    		/>
		</el-form-item>

		<el-form-item label="报名截止时间" prop="registrationDeadline">
			<el-date-picker
			type="datetime"
			@change="deadlineChange"
     		 v-model="ruleForm.registrationDeadline"
			 placeholder="截止时间"
    		/>
		</el-form-item>

		<el-form-item style="width: 100%">
		  <div style="width: 100%; display: flex; justify-content: center">
			<el-button
			  type="primary"
			   round 
			  @click="commitUpdate(ruleFormEditRef)"
			>
			 <el-icon>
          <Edit />
        </el-icon>
			  修改
			</el-button>
		  </div>
		</el-form-item>
	  </el-form>
	</div>
 </el-dialog>

	 <!-- 新增竞赛弹窗 -->
	 <el-dialog
      :title="addDialog.title"
      v-model="addDialog.visible"
      width="100%"
      @close="closeAddDialog"
    >
		<div class="box">
	  <el-form
		:model="ruleForm"
		:rules="rules"
		ref="ruleFormAddRef"
		label-width="110px"
		class="demo-ruleForm"
		size="large"
		label-position="left"
		validate-on-rule-change
		style="width: 85%"
	  >
		<el-form-item label="标题" prop="title" style="width: 100%">
		  <el-input
			style="width: 100%"
			type="text"
			v-model="ruleForm.title"
			placeholder="输入标题..."
		  ></el-input>
		</el-form-item>
  
		<el-form-item label="内容" prop="content" style="width: 100%">
		  <mavon-editor
			v-model="ruleForm.content"
			ref="md"
			@imgAdd="imgAdd"
			style="width: 100%; height: 430px"
		  />
		</el-form-item>
  
		<el-form-item label="封面" prop="coverImage">
		  <el-upload
			:action="`http://localhost:8002/file/fileoss/upload`"
			:show-file-list="false"
			:on-success="handleAvatarSuccess"
			:before-upload="beforeAvatarUpload"
			class="avatar-uploader"
		  >
			<img v-if="imageUrl" :src="imageUrl" class="avatar" />
			<!-- <el-icon v-else name="UploadFilled" class="avatar-uploader-icon"></el-icon> -->
			<el-icon v-else class="avatar-uploader-icon">
				 <UploadFilled/>
			</el-icon>
		  </el-upload>
		</el-form-item>
  
		<el-form-item label="竞赛时间" prop="competitionTime" style="width: 50%">
			<el-date-picker
     		 v-model="dateArr"
			 @change="dateChange"
			 value-format="YYYY-MM-DD HH:mm:ss"
    		 type="datetimerange"		
			 range-separator="-"
     		 start-placeholder="开始时间"
     		 end-placeholder="结束时间"
    		/>
		</el-form-item>

		<el-form-item label="报名截止时间" prop="registrationDeadline">
			<el-date-picker
			type="datetime"
			@change="deadlineChange"
     		 v-model="ruleForm.registrationDeadline"
			 placeholder="截止时间"
    		/>
		</el-form-item>

		<el-form-item style="width: 100%">
		  <div style="width: 100%; display: flex; justify-content: center">
			<el-button
			  type="primary"
			   round 
			  @click="commitAdd(ruleFormAddRef)"
			>
			 <el-icon>
          <Promotion />
        </el-icon>
			  发布
			</el-button>
		  </div>
		</el-form-item>
	  </el-form>
	</div>
 </el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { onMounted } from "vue";
import { defineComponent } from "vue";
import { useRouter } from 'vue-router';
import { getCompetitionList } from "@/api/competition";
import { competitionDel,competitionUpdate,competitionAdd } from "@/api/competition";
import { competition,competitionType,getCompetitionInfo } from "@/api/competition/type";
import competitionCard from "@/components/competitionCard/index.vue";
import axios from 'axios'
import type { FormInstance, FormRules } from 'element-plus'
import {UploadFilled,Promotion,Plus,Edit} from '@element-plus/icons-vue'
import { useUserStoreHook } from '@/store/modules/user'
import { File_API } from '@/api/file'

defineComponent({
  components: {
    competitionCard,
		UploadFilled,
		Promotion,
		Plus,
		Edit,
  },
});

const userStore = useUserStoreHook()

//定义竞赛信息列表
const competitions = ref<competition[]>([]);

//当前选中的竞赛信息
const currentCompetition = ref<any>({});

const editDialog = reactive<DialogOption>({
  visible: false
});

const addDialog = reactive<DialogOption>({
  visible: false
});


const queryParams = reactive<getCompetitionInfo>({
  pageNum: 1,
  pageSize: 10,
});

//总共页数
const pageTotal = ref(0);
//后端传来的页码数组
const pageArr = ref([]);
//当前页码
const activePager = ref(1);

const indexMethod = (index: number) => {
  return index + (activePager.value - 1) * queryParams.pageSize + 1;
};

const ids = ref([]);

		//vue3获取ref
		const ruleFormEditRef = ref<FormInstance>()
		const ruleFormAddRef = ref<FormInstance>()
	  const md = ref(null)

	  const ruleForm  = reactive<competitionType>({
		//表单
			id: 0,
			title: '',
			coverImage: '',
			competitionTime:'',
			registrationDeadline:'',
			content: '',
	})

//封面显示
	const imageUrl = ref('');

//竞赛时间value数组
	const dateArr = ref('');

onMounted(async () => {
  getCompetitions()
});

const getCompetitions  = async () => {
	try {
    const { data } = await getCompetitionList(queryParams);
    console.log("获得竞赛列表信息:", data);
    competitions.value = data.competitions;
		pageTotal.value = data.navigatepageNums[data.navigatepageNums.length - 1];
    pageArr.value = data.navigatepageNums;
  } catch (error) {
    Promise.reject(error);
  }
}


/**
 * 行checkbox change事件
 */
 function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

//删除单个
const del = async (id:number)=>{
   ids.value.push(id);
	 await ElMessageBox.confirm("确认删除竞赛?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    competitionDel(ids.value).then(() => {
      ElMessage.success("删除成功");
			getCompetitions();
    });
  });
	ids.value = [];
}

//批量删除
async function deleteClick(id?: number) {
  const adminIds = [id || ids.value] as number[];
  if (!adminIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  await ElMessageBox.confirm("确认删除竞赛?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    competitionDel(adminIds).then(() => {
      ElMessage.success("删除成功");
			getCompetitions();
			ids.value = [];
    });
  });
}

const edit =  (competition:any)=>{
   currentCompetition.value = competition;
	 editDialog.visible = true;
	 editDialog.title = '修改竞赛信息';
	 init()
}

const add =  ()=>{
	 addDialog.visible = true;
	 addDialog.title = '上传竞赛信息';
}

/**
 * 关闭弹窗
 */
 function closeEditDialog() {
   editDialog.visible = false;
	 clear();
}
function closeAddDialog() {
   addDialog.visible = false;
	 clear();
}

	  //表单验证
	  const validateContent = (rule: any, value: any, callback: any) => {
		if (value === '') {
		  return callback(new Error('请输入内容！！'))
		} else {
		  callback()
		}
	  }

	  const validateCoverImage = (rule: any, value: any, callback: any) => {
		if (value === '') {
		  return callback(new Error('请上传封面！'))
		} else {
		  callback()
		}
	  }

	  const rules = reactive<FormRules<typeof ruleForm>>({
		title: [{ required: true, message: '请输入标题！', trigger: 'blur' }],
		competitionTime: [{ required: true, message: '请输入竞赛时间！', trigger: 'blur' }],
		registrationDeadline: [{ required: true, message: '请输入报名截止时间！', trigger: 'blur' }],
		coverImage: [
		  { required: true, validator: validateCoverImage, trigger: 'blur' },
		],
		content: [
		  { required: true, validator: validateContent, trigger: 'blur' },
		],
	  })
  
   
 const init =  () => {
		ruleForm.id   =  currentCompetition.value.id ;
		ruleForm.title  =  currentCompetition.value.title ;
		ruleForm.content   =  currentCompetition.value.content ;
		ruleForm.coverImage   =  currentCompetition.value.coverImage ;
		imageUrl.value =  currentCompetition.value.coverImage ;
		ruleForm.competitionTime   =  currentCompetition.value.competitionTime ;
		dateArr.value = currentCompetition.value.competitionTime.split(" - ")
		ruleForm.registrationDeadline  = new Date(currentCompetition.value.registrationDeadline);
		// ruleForm.registrationDeadline   = currentCompetition.value.registrationDeadline;
	}

	const clear =  () => {
		ruleForm.id   =  0 ;
		ruleForm.title  =  '' ;
		ruleForm.content   =  '';
		ruleForm.coverImage   =  '' ;
		ruleForm.competitionTime   = '';
		ruleForm.registrationDeadline   =  '' ;
		imageUrl.value = '';
		dateArr.value  = '';
	}


	const handleAvatarSuccess = (res, file) => {
		imageUrl.value = URL.createObjectURL(file.raw)
		console.log(res.data.url)
		ruleForm.coverImage = res.data.url
	}
  
	  const beforeAvatarUpload = () => {}
  
	  // const $imgAdd
	  const imgAdd = (pos: any, file: any) => {
		console.log('上传图片：断点')
		// console.log(`${File_API.OTHER_URL}`)
		// 第一步.将图片上传到服务器.
		let formdata = new FormData()
		formdata.append('file', file)
		axios({
		  url: `http://localhost:8002/file/fileoss/upload`,
		  method: 'post',
		  data: formdata,
		  headers: { 'Content-Type': 'multipart/form-data' },
		}).then((res) => {
		  // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
		  console.log(res.data.data.url)
		  console.log(md)
		  md.value.$img2Url(pos, res.data.data.url)
		})
	  }
  
	const commitAdd = (formEl: FormInstance | undefined) => {
		// console.log('提交')
		if (!formEl) {
		  console.log('表单没找到')
		  return
		}
		formEl.validate(async (valid) => {
		  if (valid) {
			console.log('submit!',ruleForm)
			try {
			  const res = await competitionAdd(ruleForm)
			  console.log(res)
				getCompetitions()
				closeAddDialog()
				ElMessage.success("添加成功");
			} catch (error) {
			  Promise.reject(error)
			}
		  } else {
			console.log('error submit!')
			return false
		  }
		})
	  }

		const commitUpdate = (formEl: FormInstance | undefined) => {
		if (!formEl) {
		  console.log('表单没找到')
		  return
		}
		formEl.validate(async (valid) => {
		  if (valid) {
			console.log('submit!',ruleForm)
			try {
			  const res = await competitionUpdate(ruleForm)
			  console.log(res)
				getCompetitions()
				closeEditDialog()
				ElMessage.success("修改成功");
			} catch (error) {
			  Promise.reject(error)
			}
		  } else {
			console.log('error submit!')
			return false
		  }
		})
	  }

	const dateChange = (value:any) => {
		console.log(value)
	  ruleForm.competitionTime = `${value[0]} - ${value[1]}`;
	}

	const deadlineChange = (value:any) => {
		console.log(value)
		ruleForm.registrationDeadline = value.Format("yyyy-MM-dd hh:mm:ss");
	  }
  
	  const resetForm = (formEl: FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	  }

async function pageChange(pageNum: number) {
  queryParams.pageNum = pageNum;
  activePager.value = pageNum;
  getCompetitions();
}

async function sizeChange(sizeNum: number) {
  queryParams.pageSize = sizeNum;
  getCompetitions();
}

</script>

<style scoped>
.blank {
  width: 100%;
  height: 300px;
}

.list {
  padding-right: calc(22vw - 12%);
  padding-left: calc(22vw - 12%);

  /* margin-top: 30px; */
  background-color: white;
}

.item {
  margin: auto 0;
}

.box1{
	position: relative;
}

.buttons{
	 position: absolute;
	 right: 0;
	 top: 45%;
}

h1 {
	color: blue;
  }
  .box {
	display: flex;
	justify-content: center;
	width: 100%;
  }
 
	.pagination {
  display: flex;
  justify-content: center;
}

.pagination__item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.pagination__item.active {
  color: white;
  background-color: #4593ff;
}

</style>

<!-- 饿了么的样式写在这里避免不生效 -->
<style>
  .avatar-uploader .el-upload {
	border: 1px dashed #807d7d;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
	border-color: #409eff;
  }
  .avatar-uploader-icon {
	font-size: 28px;
	color:#409eff;
	width: 150px;
	height: 150px;
	line-height: 150px;
	text-align: center;
  }
  .avatar {
	width: 178px;
	height: 178px;
	display: block;
  }
  </style>
